"""
审计日志 | 业务层
"""

from biz.base_biz import (
    GetterBase,
    ValidatorBase,
)
from components.logger import log
from components.thread_pool import async_io_task
from mapping import AuditLogMapping
from models import PageSorting
from models.po import AuditLogPO
from models.request import AuditLogListRequest
from my_typing import *
from service import AuditLogService
from utils.decorator_utils import task_exc_catcher


class Model:
    """ 模型信息 """

    ID_FIELD: str = "audit_log_id"
    NAME: str = "审计日志"
    PO = AuditLogPO
    SERVICE = AuditLogService


class AuditLogValidator(ValidatorBase):
    """ 审计日志 | 校验器 """

    model_id_field = Model.ID_FIELD
    model_name = Model.NAME
    model_po = Model.PO
    model_service = Model.SERVICE


class AuditLogGetter(GetterBase):
    """ 审计日志 | 获取器 """

    model_mapping = AuditLogMapping
    model_validator = AuditLogValidator

    @staticmethod
    def get_list_sorting(request: AuditLogListRequest) -> DictStrInt:
        return PageSorting.get_sorting_by_map(
            {
                "ip": request.sort_by_ip,
                "model": request.sort_by_model,
                "operation": request.sort_by_operation,
                "create_time": request.sort_by_request_time,
                "user_id": request.sort_by_user_id,
            }
        )

    @classmethod
    def get_list_query(cls, request: AuditLogListRequest) -> dict:
        condition = cls.Condition()

        condition.add_eq("ip", value=request.ip)
        condition.add_eq("method", value=request.method)
        condition.add_eq("operation", value=request.operation)
        condition.add_eq("po_id_list", value=request.po_id)
        condition.add_eq("user_id", value=request.user_id)
        condition.add_eq("request_id", value=request.request_id)
        condition.add_eq("exception", value=request.exception)
        condition.add_eq("status_code", value=request.status_code)
        condition.add_gte("create_time", value=request.request_time_end)
        condition.add_lte("create_time", value=request.request_time_start)

        return condition.get_query()


class AuditLogSetter:
    """ 审计日志 | 设置器 """

    @staticmethod
    @async_io_task
    @task_exc_catcher(logger=log)
    def async_create_audit_log(audit_log_po: AuditLogPO) -> None:
        """ 异步创建 | 单条 | 审计日志 """

        AuditLogService.insert_one(audit_log_po)
